﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace ClassLibrary1
{
    public class Class1
    {
        /// <summary>    
        /// dataSet转换成Json格式,主从关系的。
        /// </summary>    
        /// <param name="dt">要转换的数据表</param>    
        /// <returns>json字符串</returns>    
        public static string DataSetToJson(DataSet ds, string strHzName, string strMxName)
        {

            DataTable dt1 = ds.Tables[strHzName];
            DataTable dt2 = ds.Tables[strMxName].Clone();
            DataTable dt3 = ds.Tables[strHzName].Clone();

            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("{ ");
            jsonBuilder.Append("\"" + dt1.TableName.ToString() + "\": ");
            jsonBuilder.Append("[");
            DataRow[] childRows;
            foreach (DataRelation relation in dt1.ChildRelations)
            {
                foreach (DataRow row in dt1.Rows)
                {
                    childRows = row.GetChildRows(relation);
                    dt2.Rows.Clear();
                    dt3.Rows.Clear();
                    foreach (DataRow dr in childRows)
                    {
                        dt2.Rows.Add(dr.ItemArray);
                    }
                    dt3.Rows.Add(row.ItemArray);
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            }
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }
    }
}
